package com.bw.controller;

import com.alibaba.fastjson.JSONObject;
import com.bw.common.GiteeUtils;
import com.bw.common.JwtUtils;
import com.bw.entity.User;
import com.bw.mapper.UserMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletResponse;

@Controller
public class GiteeLoginController {

    @Autowired
    UserMapper userMapper;


    @RequestMapping("/callbackCode.do")
    public String callback(String code, Model model, HttpServletResponse response){

        System.out.println("接收到的临时授权码"  + code);

        //根据临时授权码 获取token
        String tokenByCode = GiteeUtils.getAccessTokenByCode(code);
        System.out.println("获取到的token" + tokenByCode);

        JSONObject userInfoByToken = GiteeUtils.getGiteeUserInfoByToken(tokenByCode);
        System.out.println("获取到的用户资源（gitee账号信息）" + userInfoByToken.toJSONString());
        // 从gitee用户的资料里选择 4个字段进行存储

        String nickName = userInfoByToken.getString("name"); // 把 Name字段当做咱们自己数据库的nickname字段
        String avatarUrl = userInfoByToken.getString("avatar_url"); // 把 avatar_url当做头像
        String name = userInfoByToken.getString("login"); // 把个人空间地址当做咱们的用户名
        Integer giteeId = userInfoByToken.getInteger("id");

        //注册之前要判断 是否已经注册过
       User userDB =  userMapper.selectByName(name);

        if (userDB == null){

            userDB = new User();

            userDB.setName(name);
            userDB.setNickName(nickName);
            userDB.setGiteeId(giteeId);
            userDB.setAvatarUrl(avatarUrl);
            userMapper.addUser(userDB);

        }else { // 刷新一下数据库存储的昵称和头像

            userDB.setNickName(nickName);
            userDB.setAvatarUrl(avatarUrl);
            userMapper.updateUser(userDB);
        }

        // 颁发令牌

        String token = JwtUtils.createToken(userDB);
        Cookie cookie = new Cookie("token", token);
        response.addCookie(cookie);


        model.addAttribute("nickName",nickName);
        model.addAttribute("avatarUrl",avatarUrl);

        return "success";
    }

}
